// CSE 142, Winter 2008, Marty Stepp // // This program reads height and weight information from the console // using the Scanner, computes two users' body mass indexes (BMIs), // and compares them to find the difference between two people. // // This second version of the program also prints each person's weight // class, such as underweight or obese. // import java.util.*; // so that I can use Scanner public class BMI2 { public static void main(String[] args) { Scanner console = new Scanner(System.in); double bmi1 = processOnePerson(console); // 62.5 130.5 double bmi2 = processOnePerson(console); // 58.5 90 results(bmi1, bmi2); } // Reads the height and weight information for one person, // and returns the person's BMI. public static double processOnePerson(Scanner console) { System.out.println("Enter next person's information:"); System.out.print("height (in inches: "); double height = console.nextDouble(); System.out.print("weight (in pounds: "); double weight = console.nextDouble(); // print person's weight class (this is the new code) double bmi = computeBMI(height, weight); if (bmi >= 30.0) { System.out.println("obese"); } else if (bmi >= 25.0) { System.out.println("overweight"); } else if (bmi >= 18.5) { System.out.println("normal"); } else { System.out.println("underweight"); } System.out.println(); return bmi; } // Computes and returns a person's BMI based on their height and weight. public static double computeBMI(double height, double weight) { double bmi = weight / (height * height) * 703; return bmi; } // Displays the overall results at the end of the program. public static void results(double bmi1, double bmi2) { System.out.println("Person #1 body mass index = " + round2(bmi1)); System.out.println("Person #2 body mass index = " + round2(bmi2)); System.out.println("Difference = " + round2(Math.abs(bmi1 - bmi2))); // we could also use System.out.printf for this output: // System.out.printf("Person #1 body mass index = %.2f\n", bmi1); // System.out.printf("Person #2 body mass index = %.2f\n", bmi2); // System.out.printf("Difference = %.2f\n", Math.abs(bmi1 - bmi2)); } // Rounds the given number to 2 decimal places and returns it. // To round to a different number of places, we'd multiply/divide by // a different power of 10 (for example, by 1000 to round to 3 places). public static double round2(double result) { result = result * 100; // 33.333333333 result = Math.round(result); // 33.0 result = result / 100; // 0.33 return result; } }